package com.tanhua.server.controller;

import com.tanhua.model.domain.Result;
import com.tanhua.model.mongo.TestReport;
import com.tanhua.model.vo.Answers;
import com.tanhua.model.vo.QuestionnaireVo;
import com.tanhua.model.vo.ReportVo;
import com.tanhua.server.service.TestSoulService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/testSoul")
public class TestSoulController {

    @Autowired(required = false)
    private TestSoulService testSoulService;

    //测灵魂——问卷列表
    @GetMapping
    public ResponseEntity questionnaireList() {

        List<QuestionnaireVo> voList = testSoulService.queryTestList();
        return ResponseEntity.ok(voList);

    }

    //测灵魂——提交问卷
    @PostMapping
    public ResponseEntity submitQuestionnaire(@RequestBody Map<String, List<Answers>> paramMap) {
        List<Answers> answers = paramMap.get("answers");   //得到传入的answers集合

        //得到问题id->获得问卷id
        Long questionId = 0l;
        for (Answers answer : answers) {
            questionId = Long.valueOf(answer.getQuestionId());
            break;
        }
        Long questionnaireId = testSoulService.getQuestionnaireId(questionId);

        testSoulService.unlockNext(questionnaireId);   //根据当前用户提交的问卷id，解锁下一个问卷

        Integer totalScore = testSoulService.getTotalScore(answers);    //计算总得分
        Result result = testSoulService.getResultByScore(totalScore, questionnaireId);   //根据得分和问卷id得到result
        TestReport testReport = testSoulService.getReport(result, questionnaireId, totalScore);   //根据结果，生成一个专属于用户的报告表
        String reportId = testReport.getId().toHexString();     //返回报告id
        return ResponseEntity.ok(reportId);
    }

    //测灵魂——查看结果
    @GetMapping("/report/{id}")
    public ResponseEntity getReportVo(@PathVariable("id") String reportId) {
        ReportVo reportVo = testSoulService.getReportVo(reportId);
        return ResponseEntity.ok(reportVo);
    }


}
